package com.hongkuncheng.cms.helper;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 安全加密解密类
 *
 * @author 洪坤成
 */
public class SecurityHelper {

    /**
     * MD5加密
     *
     * @param input
     * @return
     */
    public static String md5Encrypt(String input) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = input.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static final Base64.Encoder encoder = Base64.getEncoder();
    private static final Base64.Decoder decoder = Base64.getDecoder();

    /**
     * Base64加密
     *
     * @param input
     * @return
     */
    public static String b64Encrypt(String input) {
        String result = "";
        try {
            byte[] bytes = input.getBytes("UTF-8");
            result = encoder.encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Base64解密
     *
     * @param input
     * @return
     */
    public static String b64Decrypt(String input) {
        String result = "";
        try {
            result = new String(decoder.decode(input), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    //AES默认key
    private static final String aesDefaultKey = "hongkuncheng1987";

    /**
     * AES加密
     *
     * @param input
     * @return
     */
    public static String aesEncrypt(String input) {
        return aesEncrypt(input, aesDefaultKey);
    }

    /**
     * AES加密
     *
     * @param input
     * @param key
     * @return
     */
    public static String aesEncrypt(String input, String key) {
        String result = null;
        //创建一个密钥对象，第1个参数是key的字节数组，第2参数是算法
        SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        try {
            //创建一个加密算法对象，参数为填充模式
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            //初始化加密算法对象，第1个参数是算法动作（是加密或者解密），第2个参数就是密钥对象
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            //执行加密算法，参数是原文的字节数组
            byte[] data = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8));
            //将字节数组转换为字符串
            result = Base64.getEncoder().encodeToString(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            return result;
        }
    }

    /**
     * AES解密
     *
     * @param input
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String input) {
        return aesDecrypt(input, aesDefaultKey);
    }

    /**
     * AES解密
     *
     * @param input
     * @param key
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String input, String key) {
        String result = null;
        //创建一个密钥对象，第1个参数是key的字节数组，第2参数是算法
        SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        try {
            //创建一个加密算法对象，参数为填充模式
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            //初始化加密算法对象，第1个参数是算法动作（是加密或者解密），第2个参数就是密钥对象
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            //执行加密算法，参数是密文的字节数组
            byte[] data = cipher.doFinal(Base64.getDecoder().decode(input));
            //将字节数组转换为字符串
            result = new String(data, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            return result;
        }
    }



}
